package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 *
 * @author long
 * @date 2025-09-30
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private ContractMapper contractMapper;


    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }
    /**
     * 入住申请
     * @param checkInApplyDto
     */
    @Override
    @Transactional
    public void apply(CheckInApplyDto checkInApplyDto) {
        //1 校验老人是否已经入住，如果已经入住，直接结束
        checkElderCheckIn(checkInApplyDto);
        //2 更新床位状态为已入住
        Bed bed = bedMapper.selectById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        //3 新增或者更新老人信息
        Elder elder = insertOrUpdateElder(checkInApplyDto, bed);
        //4 新增签约办理(合同)
        saveContract(checkInApplyDto, elder);
        //5 新增入住信息
        CheckIn checkIn = saveCheckIn(checkInApplyDto, elder, bed);
        //6 新增入住配置
        saveCheckInConfig(checkInApplyDto.getCheckInConfigDto(), checkIn);
    }

    @Override
    public CheckInDetailVo deail(Long id) {
        //根据入住id查询入住详情的startDate和endDate bedNumber remark转化为集合封装到elderFamilyVoList 和配置表的数据  返回老人id
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        //将checkIn对象中的remake转化为集合封装到 elderFamilyVoList中
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class);
        CheckInConfigVo checkInConfigVo = checkInConfigMapper.selectCheckInConfigByCheckInId(id);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        //查询老人的基本信息
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder, checkInElderVo);

        //根据老人id查询合同的信息
        Contract contract = contractMapper.selectOne(new LambdaQueryWrapper<Contract>().eq(Contract::getElderId, checkIn.getElderId()));

        //封装返回数据
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setContract(contract);

        return checkInDetailVo;

    }


    private void saveCheckInConfig(CheckInConfigDto checkInConfigDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto, checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }


    private CheckIn saveCheckIn(CheckInApplyDto checkInApplyDto, Elder elder, Bed bed) {
        CheckIn checkIn = new CheckIn();
        //设置老人的信息
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        //设置入住信息
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(bed.getBedNumber());
        //设置家属信息
        List<ElderFamilyDto> elderFamilyDtoList = checkInApplyDto.getElderFamilyDtoList();
        checkIn.setRemark(JSON.toJSONString(elderFamilyDtoList));
        //新增入住信息
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    private void saveContract(CheckInApplyDto checkInApplyDto, Elder elder) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        contract.setElderId(elder.getId().intValue());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        //设置状态。如果开始时间比当前时间小，则设为已生效
        if(LocalDateTime.now().isAfter(contract.getStartDate())){
            contract.setContractNumber("HT"+CodeGenerator.generateContractNumber());
        }
        contractMapper.insert(contract);
    }

    private Elder insertOrUpdateElder(CheckInApplyDto checkInApplyDto, Bed bed) {
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInElderDto(), elder);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        //查旬老人  select * from elder where id_card_no = #{idCardNo}
        Elder elderDb = elderMapper.selectOne(new LambdaQueryWrapper<Elder>().eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo()));
        if(elderDb != null){
            //如果存在，则更新
            elder.setId(elderDb.getId());
            elderMapper.updateById(elder);
        }else{
            //不存在新增
            elderMapper.insert(elder);
        }

        return elder;
    }

    private void checkElderCheckIn(CheckInApplyDto checkInApplyDto) {
        //根据身份证号查询老人
        LambdaQueryWrapper<Elder> elderLambdaQueryWrapper = new LambdaQueryWrapper<Elder>();
        elderLambdaQueryWrapper.eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo());
        elderLambdaQueryWrapper.eq(Elder::getStatus,1);
        Elder elder = elderMapper.selectOne(elderLambdaQueryWrapper);
        if(elder != null){
            //该老人已经入住
            throw new BaseException("该老人已经入住");
        }
    }
}
